import { reactive, toRaw } from 'vue'

// 分页钩子函数
interface Options {
    page?: number
    pageSize?: number
    fetchFn: object & {
        get: (params: any) => Promise<any>
    }
    params?: Record<any, any>
    firstLoading?: boolean
}

export function usePaging(options: Options) {
    const { page = 1, pageSize = 15, fetchFn, params = {}, firstLoading = false } = options
    // 分页初始参数
    const paramsInit: Record<any, any> = Object.assign({}, toRaw(params))

    // 分页数据
    const pagination = reactive({
        page,
        pageSize,
        loading: firstLoading,
        total: 0,
        list: [] as any[]
    })

    // 请求分页接口
    const getList = async () => {
        pagination.loading = true

        const res = await fetchFn.get({
            page: pagination.page,
            pageSize: pagination.pageSize,
            ...params
        })

        pagination.total = res.total ?? 0
        pagination.list = res.data ?? []
        pagination.loading = false
    }

    // 重置为第一页
    const resetPage = () => {
        pagination.page = 1

        getList()
    }

    // 重置参数
    const resetParams = () => {
        Object.keys(paramsInit).forEach((item) => {
            params[item] = paramsInit[item]
        })

        getList()
    }

    return {
        pagination,
        getList,
        resetParams,
        resetPage
    }
}
